// 封装购物车模块
import { defineStore } from 'pinia'
import { ref,computed } from 'vue'
import { insertCartAPI,getCartListAPI,delCartAPI } from '@/apis/cart'
import { useUserStore } from '@/stores/user';



export const useCartStore = defineStore('cart',()=>{
  // 1. 定义state - cartList
  const cartList = ref([])
  
  //抽离获取最新购物车列表
  const updateNewList = async ()=>{
    const res = await getCartListAPI()
    cartList.value = res.cart_goods
    //console.log(cartList.value);
  }
  const userStore = useUserStore()
  const isLogin = computed(()=>userStore.userInfo.token)
  // 2. 定义action - addCart
  const addCart = async (goods)=>{
    //console.log('添加',goods);
    const {id,count}=goods
    if(isLogin.value){

     await insertCartAPI({id,count})
      
      updateNewList()
      //await postCheckInfoAPI()
    }else {
      const item = cartList.value.find((item) => goods.id === item.id) 
      if (item) {
        // 找到了
        item.count++
      } else {
        // 没找到
        cartList.value.push(goods)
      }
    }
    
    /* const item = cartList.value.find((item) => goods.id === item.id) 
    if (item) {
      // 找到了
      item.count++
    } else {
      // 没找到
      cartList.value.push(goods)
    } */
  }
  // 删除购物车  skuId
  const delCart = async (id) => {  
    if(isLogin.value){
      await delCartAPI([id])
      
      updateNewList()
      
    }else {
      const idx = cartList.value.findIndex((item) => id === item.id) 
      cartList.value.splice(idx, 1)
    }
    /* const idx = cartList.value.findIndex((item) => id === item.id) 
    cartList.value.splice(idx, 1) */
  }

  //清除购物车
  const clearCart = ()=>{
    cartList.value = []
  }
  

  //单选功能
  const singleCheck = (id,is_selected)=>{
    const item = cartList.value.find((item) => item.id === id)
    item.is_selected = is_selected
  }

  //计算价格
  //1，总的数量   所有项的count 和
  const allCount = computed(()=>cartList.value.reduce((a,c)=>a + c.goods_number,0))
  //2，总价       所有项的count*price 和
  const allPrice = computed(()=>cartList.value.reduce((a,c)=>a + c.goods_number * c.price,0))
  // 3. 已选择数量
  const selectedCount = computed(() => cartList.value.filter(item => item.is_selected).reduce((a, c) => a + c.goods_number, 0))
  // 4. 已选择商品价钱合计
  const selectedPrice = computed(() => cartList.value.filter(item => item.is_selected).reduce((a, c) => a + c.goods_number * c.price, 0))

  //全选功能
  const allCheck = (is_selected) => {
    cartList.value.forEach(item => item.is_selected = is_selected)
  }
  //是否全选
  const isAll = computed(() => cartList.value.every((item) => item.is_selected))

  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    allCheck,
    isAll,
    selectedCount,
    selectedPrice,
    clearCart,
   
  }
}, {
  persist: true,
})